import { Button } from 'antd';

import DeleteIcon from '@/assets/icons/delete.svg';

import { LogicExpression } from '../Rules';
import { ValueSelector, ValueSelectorProps } from '../Rules/value';

interface MultipleAssignmentsProps extends Omit<ValueSelectorProps, 'value' | 'onChange'> {
  value?: LogicExpression[];
  onChange?: (value: LogicExpression[]) => void;
}

const getFieldId = () => {
  return 'id_' + String(Math.random()).slice(-5);
};

export const MultipleAssignments = memo<MultipleAssignmentsProps>((props) => {
  const { value = [], onChange, ...rest } = props;
  return (
    <div className="multiple-assignments flex flex-col gap-8">
      {value?.map?.((item, index) => {
        const key = item.id || JSON.stringify(item || {}) + index;
        return (
          <div key={key} className="flex items-center">
            <ValueSelector
              onChange={(v) => {
                onChange?.(value.map((val, i) => (i === index ? v! : val)));
              }}
              className="flex-1"
              {...rest}
              value={item}
              key={index}
            />
            <DeleteIcon
              onClick={() => {
                onChange?.(value.filter((_, i) => i !== index));
              }}
              width={18}
              height={18}
              className="ml-8 cursor-pointer"
            />
          </div>
        );
      })}

      <Button
        type="dashed"
        size="small"
        onClick={() => {
          onChange?.([...value, { id: getFieldId() }]);
        }}>
        新增赋值
      </Button>
    </div>
  );
});
